import 'package:flutter/material.dart';
import 'package:shortmovieapp/Common.dart';
import 'package:shortmovieapp/data/localData.dart';
import 'package:shortmovieapp/data/viewData.dart';
import 'package:shortmovieapp/myController/RequestServerController.dart';

class MovieItemWidget extends StatelessWidget {
  final MovieItemData data;
  final double itemWidth;
  const MovieItemWidget({super.key, required this.data, this.itemWidth = 100});

  void onClickItem(BuildContext context) async{
    Debug.log("on click ${data.movieId}");

    //默认打开第一集，TODO.读取本地保存进度
    int defaultIndedx = 0;
    MovieData? shortMoviesData =
       await RequestServerController().getShortMovieData(data.title);

    if (shortMoviesData != null) {
      Map<String, dynamic> arguments = {
        "defaultIndex": defaultIndedx,
        "movieDatas": shortMoviesData,
      };
      Debug.log("req movie data end show video page");
      Navigator.of(context).pushNamed(MyPageRoute.video, arguments: arguments);
    } else {
      Debug.log("获取影片出错");
    }
  }

  @override
  Widget build(BuildContext context) {

    Debug.log("显示影片：${data}");

    return Container(
      width: itemWidth,
      alignment: Alignment.center,
      child: TextButton(
          style: ButtonStyle(
              overlayColor: MaterialStateProperty.all(Colors.transparent)),
          onPressed: () => onClickItem(context),
          child: Stack(children: [
            Align(
              alignment: Alignment.topLeft,
              child: Stack(
                children: [
                  Container(
                    width: itemWidth,
                    height: itemWidth,
                    decoration: BoxDecoration(
                        image: DecorationImage(
                            image: NetworkImage(data.iconUrl),
                            fit: BoxFit.cover)),
                  ),
                  Positioned(
                      bottom: 5,
                      right: 5,
                      child: Text(
                        "${data.watchTimes}播放",
                        style:
                            const TextStyle(fontSize: 10, color: Colors.white),
                      ))
                ],
              ),
            ),
            Positioned(
                left: 0,
                top: itemWidth,
                child: SizedBox(
                    height: 40,
                    child: Column(
                      children: [
                        Container(
                            width: double.maxFinite,
                            height: 20,
                            alignment: Alignment.centerLeft,
                            child: Text(data.title,
                                style: const TextStyle(
                                    fontSize: 12, color: Colors.white))),
                        Container(
                          width: double.maxFinite,
                          height: 15,
                          alignment: Alignment.centerLeft,
                          child: Text(
                            "${data.typeName}·${data.episodeCount}集",
                            style: const TextStyle(
                                fontSize: 12, color: Colors.white30),
                          ),
                        )
                      ],
                    ))),
          ])),
    );
  }
}

class MovieItemsGrid extends StatelessWidget {
  final List<MovieItemData> itemDatas;
  const MovieItemsGrid({super.key, required this.itemDatas});

  @override
  Widget build(
    BuildContext context,
  ) {
    double itemWidth = 120;

    return GridView.extent(
      maxCrossAxisExtent: itemWidth,
      //crossAxisCount: 3,
      padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
      //crossAxisCount: 3,
      scrollDirection: Axis.vertical,
      mainAxisSpacing: 10,
      crossAxisSpacing: 5,
      childAspectRatio: 2.0 / 3.0,
      children: itemDatas
          .map((e) => MovieItemWidget(
                data: e,
                itemWidth: itemWidth,
              ))
          .toList(),
    );
  }
}

class searchButton extends StatelessWidget {
  final double size;
  final Alignment alignment;
  final Function? onClick;

  const searchButton(
      {super.key,
      this.onClick,
      this.size = 30,
      this.alignment = Alignment.center});

  @override
  Widget build(BuildContext context) {
    return Container(
        width: size,
        height: size, // double.maxFinite,
        alignment: alignment,
        child: IconButton(
          onPressed: () {
            Debug.log("on click search");
            onClick?.call();
            //Navigator.of(context).pushNamed(MyPageRoute.seach);
          },
          icon: const Icon(Icons.search),
        ));
  }
}

//弹窗
Future<int>? showSimpleDialog(BuildContext context, String message) async {
  var result = await showDialog(
      barrierDismissible: true, //表示点击灰色背景的时候是否消失弹出框
      context: context,
      builder: (context) {
        return SimpleDialog(
          title: Text(message),
          children: <Widget>[
            // SimpleDialogOption(
            //   child: const Text("取消"),
            //   onPressed: () {
            //     print("Option 取消");
            //     Navigator.pop(context, 0);
            //   },
            // ),
            const Divider(),
            SimpleDialogOption(
              child: const Text("确定"),
              onPressed: () {
                print("Option 确定");
                Navigator.pop(context, 1);
              },
            ),
          ],
        );
      });
  Debug.log("showDialog:$result");
  return result;
}

void showMyDialog(BuildContext context, String title, String content,
    Function()? onClose) async {
  await showDialog(
      barrierDismissible: true, //表示点击灰色背景的时候是否消失弹出框
      context: context,
      builder: (context) {
        return MyDialog(
            title: title,
            onClosed: () {
              //Debug.log("关闭");
              Navigator.of(context).pop();
              onClose?.call();
            },
            content: content);
      });
}

class MyDialog extends Dialog {
  String title;
  String content;
  Function()? onClosed;
  MyDialog(
      {Key? key,
      required this.title,
      required this.onClosed,
      this.content = ""})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: Center(
          child: Container(
        height: 300,
        width: 300,
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(10)
          ,color: Colors.white),
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(10),
              child: Stack(
                children: <Widget>[
                  Align(
                    alignment: Alignment.center,
                    child: Text(title,
                        style: const TextStyle(color: Colors.black)),
                  ),
                  // Align(
                  //   alignment: Alignment.bottomCenter,
                  //   child:
                  //   // InkWell(
                  //   //   onTap: onClosed,
                  //   //   child: const Icon(Icons.close),
                  //   // ),
                  // )
                ],
              ),
            ),
            const Divider(),
            Container(
              padding: const EdgeInsets.all(10),
              height: 180,
              width: double.infinity,
              child: Text(content,
                textAlign: TextAlign.left,
                style: const TextStyle(color: Colors.black),
              ),
            ),
            Container(
              decoration:
                  BoxDecoration(borderRadius: BorderRadius.circular(10)),
              width: 200,
              height: 40,
              child: ElevatedButton(
                onPressed: onClosed,
                child: const Text("确定"),
              ),
            )
          ],
        ),
      )),
    );
  }
}


class MyInput extends StatefulWidget {
  final String? hint;
  final ValueChanged<String>? onValueChanged;
  final ValueChanged<bool>? focusChanged;
  final bool lineStretch;
  final bool obscureText;
  final TextInputType keyboardType;
  final String? initialText;
  final Color? backgroundColor;
  final Color textColor;
  final Color cursorColor;

  const MyInput(
      {super.key,
      this.hint,
      this.onValueChanged,
      this.focusChanged,
      this.lineStretch = false,
      this.obscureText = false,
      this.keyboardType = TextInputType.text,this.initialText,
      this.backgroundColor,this.textColor = Colors.white
      ,this.cursorColor = Colors.white});

  @override
  State createState() => _MyInputState();
}

class _MyInputState<T extends MyInput> extends State<MyInput> {
  FocusNode? _focusNode;
  late TextEditingController textcontroller;
  @override
  void initState() {
    _focusNode = FocusNode();
     textcontroller = TextEditingController(text: widget.initialText);

    super.initState();
  }

  @override
  void dispose() {
    _focusNode?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return inputField();
  }

  Widget inputField() {
   
    return Expanded(
        child: TextField(
      controller:textcontroller,
      focusNode: _focusNode,
      onChanged: widget.onValueChanged,
      obscureText: widget.obscureText,
      keyboardType: widget.keyboardType,
      autofocus: !widget.obscureText,
      cursorColor: widget.cursorColor,
      style:  TextStyle(fontSize: 14, color: widget.textColor),
      decoration: InputDecoration(
          contentPadding: const EdgeInsets.only(left: 20, right: 20),
          border: InputBorder.none,
          hintText: widget.hint ?? "",
          hintStyle: const TextStyle(fontSize: 14, color: Colors.grey)),
    ));
  }
}

// class PageAppBar extends StatelessWidget {

//   String title;
//   String? rightBtnText;
//   Function(BuildContext context)? onRightBtnClick;
//   PageAppBar({super.key,required this.title,this.onRightBtnClick,this.rightBtnText});

//   @override
//   Widget build(BuildContext context) {
//     return  AppBar(
//           titleTextStyle:const TextStyle(fontSize: 16) ,
//           title: Text(title),
//           centerTitle: true,
//           actions: [
//            rightBtnText != null? TextButton(
//                 onPressed: () => onRightBtnClick?.call(context),
//                 child:  Text(rightBtnText!)):Container()
//           ],
//         );
//   }
// }